/**
 * Created by Weizehua on 2017/1/25.
 */
import {HasherFacotry} from "./Factory/HasherFacotry";
import {AliOSSFactory} from "./Factory/AliOSSFactory";
import {AliDayuSMSFactory} from "./Factory/AliDayuSMSFactory";
import {GeetestFactory} from "./Factory/GeetestFactory";
import {Injector} from "ts.di";
import {Database} from "./Core/Database/Database";
import {HttpsServer} from "./https_server";
import {UserHandler} from "./User/UserHandler";
import {GeetestHandler} from "./Geetest/GeetestHandler";
import {Connection, ConnectionOptions} from "typeorm";
import {UploadHandler} from "./Upload/UploadHandler";
import {ImageHandler} from "./Image/ImageHandler";
import {AlbumHandler} from "./Album/AlbumHandler";
import {UserInfoHandler} from "./UserInfo/UserInfoHandler";
import {FollowInfoHandler} from "./FollowInfo/FollowInfoHandler";
import {SearchHandler} from "./User/SearchHandler";
import {serverOptions, serverPort, typeormOptions} from "../Config/Config";

export class Main {
    async exec() {
        await this.loadFactories();
        await this.connectToDatabase(typeormOptions);
        await this.loadHandlers();
        await this.runHttpServer();
    }

    async loadFactories() {
        // Utilities' factories
        Injector.get(HasherFacotry);

        // 3rd party service factories
        Injector.get(AliOSSFactory);
        Injector.get(AliDayuSMSFactory);
        Injector.get(GeetestFactory);

    }

    async connectToDatabase(options: ConnectionOptions) {
        let database = Injector.get(Database);
        Injector.setSingleton(Connection, await database.connect(options));
    }

    async loadHandlers() {
        Injector.get(GeetestHandler);
        Injector.get(UserHandler);
        Injector.get(UploadHandler);
        Injector.get(ImageHandler);
        Injector.get(AlbumHandler);
        Injector.get(UserInfoHandler);
        Injector.get(FollowInfoHandler);
        Injector.get(SearchHandler);
    }

    async runHttpServer() {
        let server = Injector.get(HttpsServer);
        await server.exec(serverOptions, serverPort, 10);
    }

}

